var log = log4javascript.getLogger("BACKGROUNDPAGE");
var layout = new log4javascript.PatternLayout("%c %d{HH:mm:ss} %-5p - %m%n");
var appender = new log4javascript.PopUpAppender();
appender.setLayout(layout);
log.addAppender(appender);

log.debug("logging...");

//var popupPort = chrome.extension.connect({name: "results"});

// funktioniert leider asynchron nicht richtig
var tabs = [];
var portsMap = {};

//benutze Ports hier
//hier kommt der request von der popup seite rein. als Antwort sollte ein Array der passenden responses gesendet werden
//darin muessen auch die tab-ids enthalten sein, damit von der popup-seite in den tab gesprungen werden kann.
chrome.extension.onConnect.addListener(function(popupPort) {
    //chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    log.info("Connect...");

    //   log.debug(sender.tab ? "from a tab with the url:" + sender.tab.url : "from the extension");
    if (popupPort.name == "requestPort") {

        log.info("Connect on requestPort...");

        popupPort.onMessage.addListener(function(request) {

            if (request.query) {

                log.debug("request.query: " + request.query);

                if (tabs.length == 0) {
                    // wie konnte das extension icon ohne zugehoerigen tab geklickt werden?
                    log.error("No tabs found");
                } else {
                    log.debug("found: " + tabs.length + " tabs.");
                }
                for (i = 0; i < tabs.length; i++) {

                    var tab = tabs[i];

                    log.debug("connecting to tab[i:" + i + "] with id: " + tab.id);

                    var tabPort = chrome.tabs.connect(tab.id, null);
                    tabPort.name = tab.id;
                    log.debug("tabPort.name: " + tabPort.name);

                    log.debug("tabPort.postMessage...");
                    tabPort.postMessage({query: request.query, tab: tab});
                    log.debug("tabPort.postMessage...done");

                    tabPort.onMessage.addListener(function(data) {

                        log.debug("onMessage listener data: " + odump(data));

                        if (data.hitcount > 0) {

                            log.info("Posting response to popupPort: " + popupPort.name);
                            popupPort.postMessage(data);

                        }

                    });


                }


            }

        });

    }


});

function openTabSearch() {
    log.debug("Opening smart search");
    openPopup(300, 500, chrome.extension.getURL('popup.html'));
}

function openPopup(width, height, url) {
    var w = width;
    var h = height;
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);

    if (window.settingsWin) {
        window.settingsWin.close();
        window.settingsWin = null;
    }

    window.settingsWin = window.open(url, url, 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
    window.settingsWin.focus();
}


chrome.extension.onConnect.addListener(function(port) {

    log.debug("a) port: connected: " + port.name);
    //    log.debug("port: " + odump(port));

    if (port.name == 'smartsearch') {


        port.onMessage.addListener(function(data) {
            if (data.command == "openSmartSearch")
                openTabSearch();
        });
    }
});

chrome.extension.onConnect.addListener(function(port) {

    log.debug("b) port: connected: " + port.name);


    if (port.name != 'smartsearch' && data.query != null)

        log.debug("!smartsearch -> port: connected");

    port.onMessage.addListener(function(data) {
        log.debug("onMessage listener data: " + odump(data));
    });
});

chrome.tabs.onCreated.addListener(function(tab) {
    log.info('tabs.onCreated --'
            + ' window: ' + tab.windowId
            + ' tab: ' + tab.id
            + ' index: ' + tab.index
            + ' url: ' + tab.url);

    tabs.push(tab);
    //
    //    for (var i = 0; i < tabs.length; i++) {
    //        log.info('nach push: tabs:' + tabs[i].id);
    //    }
});


//TODO: remove implementieren

chrome.tabs.onRemoved.addListener(function(tabId) {

    log.debug('tabs.onRemoved tab.id: ' + tabId);

    //    for (var i = 0; i < tabs.length; i++) {
    //        log.info('vorher: tabs:' + tabs[i].id);
    //    }

    removeById(tabId, tabs);

    //    for (i = 0; i < tabs.length; i++) {
    //        log.info('nachher: tabs:' + tabs[i].id);
    //    }
});

function removeById(tabId, array) {

    for (var i = 0; i < array.length; i++) {

        //        log.debug(i + ": array[i].id: " + array[i].id + " tabId: " + tabId);

        if (array[i].id == tabId) {

            //            log.debug(i + ": remove tabId: " + tabId);

            array.splice(i, 1);
            //            log.debug("removed tab ");
        }
    }

    //    for (var i = 0; i < array.length; i++) {
    //        log.info('removeById: tabs:' + array[i].id);
    //    }
}
